//
//  XLSettingViewController.m
//  XiangLove
//
//  Created by 李传坤 on 2018/6/12.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "XLSettingViewController.h"
#import <ReactiveCocoa.h>
#import "XLSWTableViewCell.h"
#import <YYCache.h>
#import <YYWebImageManager.h>
#import <YYDiskCache.h>
#import "BMHAboutMeController.h"
#import "XLV2LoginViewController.h"
#import "XLBlackListVC.h"

@interface UITableViewCell (click)
@property (nonatomic, copy) void(^clickBlock)(void);
@end

@implementation UITableViewCell (click)
- (void (^)(void))clickBlock {
    return objc_getAssociatedObject(self, @"clickBlock");
}

- (void)setClickBlock:(void (^)(void))clickBlock {
    objc_setAssociatedObject(self, @"clickBlock", clickBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
@end

@interface XLSettingViewController ()<UITableViewDelegate, UITableViewDataSource,UITextFieldDelegate>{
    NSInteger switchButton;
}
@property (nonatomic, strong) UITableView     *tableView;
@property (nonatomic, strong) UISwitch        *sw;
@property (nonatomic, copy  ) NSString        *videoHint;
@property (nonatomic, strong) NSArray         *cellArray;
@property (nonatomic, strong) UITableViewCell *swithCell;//
@property (nonatomic, strong) UITableViewCell *huancunCell;//
@property (nonatomic, strong) UITableViewCell *blackListCell;//
@property (nonatomic, strong) UITableViewCell *aboutCell;//
@property (nonatomic, strong) UITableViewCell *setCell;//
@property (nonatomic, copy  ) NSString        *voiceSwitchValue;
@property (nonatomic, copy  ) NSString        *videoSwitchValue;
@property (nonatomic,  copy ) void(^setChatSucessBlock)(void);
@property (nonatomic,  copy ) void(^setChatFailBlock)(void);
@property (nonatomic, assign) NSInteger        bytes;
@property (nonatomic, strong) UITextField *password;
@end

@implementation XLSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    switchButton = 0;
     [self showBackButton:NULL];
    self.navigationItem.title = @"设置";
    _videoSwitchValue = _chatStatus;
    [self setupView];
    [self setupCellArray];
    // Do any additional setup after loading the view.
}
#pragma mark - initUI
- (void)setupView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.separatorColor = RGB_HEX(0xEEEEEE);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.sectionHeaderHeight = 10;
    self.tableView.sectionFooterHeight = 0.01;
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, ScreenHeight-250, 200, 250);
    [leftButton addTarget:self action:@selector(selectEnvirment) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftButton];
    _password = [[UITextField alloc]init];
    _password.placeholder = @"输入密码";
    _password.delegate = self;
    _password.frame = CGRectMake(10, 250, ScreenWidth, 50);
    [self.view addSubview:_password];
    _password.hidden = YES;
    
}
- (void)selectEnvirment{
    switchButton ++;
    if (switchButton == 15) {
        _password.hidden = NO;
    }
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
    if ([_password.text isEqualToString:@"123456"]) {
        if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"isTestUrl"]isEqualToString:@"yes"]) {
            [[NSUserDefaults standardUserDefaults]setObject:@"no" forKey:@"isTestUrl"];
        }else{
            [[NSUserDefaults standardUserDefaults]setObject:@"yes" forKey:@"isTestUrl"];
        }
        [[NSUserDefaults standardUserDefaults] synchronize];
        [MBProgressHUD showContent:@"切换成功请重启APP"];
        _password.hidden = YES;
    }
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.cellArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *sectionArray = self.cellArray[section];
    return sectionArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.cellArray[indexPath.section][indexPath.row];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;

}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    //    if (section == 0) {
    //        return 10;
    //    }else if (section == 1){
    //        return 10;
    //    }else if (section == 2){
    //        return 10;
    //    }else if (section == 3) {
    //        return 10;
    //    }else if (section == 4) {
    return 10;
    //    }
    //    return 0.01;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UITableViewCell *cell = self.cellArray[indexPath.section][indexPath.row];
    
    if (cell.clickBlock) {
        cell.clickBlock();
    }
}

#pragma mark - switch Action
- (void)switchAction:(UISwitch *)sender {
    
    @weakify(self);
    if (sender.on) {
        self.videoHint = @"开启视聊";
        self.videoSwitchValue = @"1";
        self.chatStatus = @"1";
        self.setChatSucessBlock = ^{
            @strongify(self);
            self.sw.on = YES;
        };
        self.setChatFailBlock = ^{
            @strongify(self);
            self.sw.on = NO;
        };
        
    }else {
        self.videoHint = @"关闭视聊";
        self.videoSwitchValue = @"0";
        self.chatStatus = @"0";
        self.setChatSucessBlock = ^{
            @strongify(self);
            BMHLog(@"我关闭视频");
            self.sw.on = NO;
        };
        self.setChatFailBlock = ^{
            @strongify(self);
            self.sw.on = YES;
        };
    }
    [self toSaveUserInfo];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)setupCellArray {
    @weakify(self);
    //私聊开关
    XLSWTableViewCell *swcell = [[XLSWTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([XLSWTableViewCell class])];
    swcell.selectionStyle = UITableViewCellSelectionStyleNone;
    swcell.textLabel.font = [UIFont systemFontOfSize:16];
    swcell.textLabel.textColor = kBlackColor;
    swcell.textLabel.text = @"勿扰";
    swcell.accessoryType = UITableViewCellAccessoryNone;
    swcell.backgroundColor = RGB_HEX(0xffffff);
    _sw = [[UISwitch alloc] init];
    [_sw addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventTouchUpInside];
    [swcell.contentView addSubview:_sw];
    [_sw mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(swcell.contentView.mas_right).offset(-6);
        make.centerY.equalTo(swcell.contentView);
        make.size.mas_equalTo(CGSizeMake(60, 30));
    }];
    UILabel *textLabel = [[UILabel alloc]initWithFrame:CGRectMake(52, 8, 150, 28)];
    textLabel.text = @"是否接收视频邀请";textLabel.font = [UIFont systemFontOfSize:13];
    textLabel.textColor = kLightGrayColor;
    [swcell.contentView addSubview:textLabel];
    _sw.on = [self.videoSwitchValue integerValue];
    _swithCell = swcell;
    //黑名单
    UITableViewCell *blackList = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:NSStringFromClass([UITableViewCell class])];
    blackList.selectionStyle = UITableViewCellSelectionStyleNone;
    blackList.textLabel.font = [UIFont systemFontOfSize:16];
    blackList.textLabel.textColor = kBlackColor;
    blackList.textLabel.text = @"黑名单";
    blackList.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    blackList.backgroundColor = RGB_HEX(0xffffff);
    blackList.clickBlock = ^{
        @strongify(self);
        XLBlackListVC *vc = [[XLBlackListVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    };
    _blackListCell = blackList;
    //缓存
    UITableViewCell *huanchuncell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:NSStringFromClass([UITableViewCell class])];
    huanchuncell.selectionStyle = UITableViewCellSelectionStyleNone;
    huanchuncell.textLabel.font = [UIFont systemFontOfSize:16];
    huanchuncell.textLabel.textColor = kBlackColor;
    huanchuncell.textLabel.text = @"清除缓存";
    huanchuncell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    huanchuncell.detailTextLabel.text = [self calculateCacheSize];
    huanchuncell.detailTextLabel.font = [UIFont systemFontOfSize:17];
    huanchuncell.detailTextLabel.textColor = RGB_HEX(0x9395a2);
    huanchuncell.accessoryType = UITableViewCellAccessoryNone;
    huanchuncell.backgroundColor = RGB_HEX(0xffffff);
    huanchuncell.clickBlock = ^{
        @strongify(self);
        YYWebImageManager *manager = [YYWebImageManager sharedManager];
        [MBProgressHUD showMessage:@"" toView:self.view];
        [manager.cache.diskCache removeAllObjectsWithBlock:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUDForView:self.view];
                self.huancunCell.detailTextLabel.text = @"0 M";
            });
        }];
    };
    _huancunCell = huanchuncell;
    
    //关心与我们
    UITableViewCell *guanyucell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:NSStringFromClass([UITableViewCell class])];
    guanyucell.selectionStyle = UITableViewCellSelectionStyleNone;
    guanyucell.textLabel.font = [UIFont systemFontOfSize:16];
    guanyucell.textLabel.textColor = kBlackColor;
    guanyucell.textLabel.text = @"关于我们";
    guanyucell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    guanyucell.backgroundColor = RGB_HEX(0xffffff);
    guanyucell.clickBlock = ^{
        @strongify(self);
        BMHAboutMeController *vc = [[BMHAboutMeController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    };
    _aboutCell = guanyucell;
    
    //退出
    UITableViewCell *setcell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([UITableViewCell class])];
    setcell.selectionStyle = UITableViewCellSelectionStyleNone;
    setcell.textLabel.text = @"切换账号";
    setcell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    setcell.textLabel.font = [UIFont systemFontOfSize:16];
    setcell.textLabel.textColor = kBlackColor;
    setcell.backgroundColor = RGB_HEX(0xffffff);
    setcell.clickBlock = ^{
        @strongify(self);
        XLV2LoginViewController *vc = [[XLV2LoginViewController alloc] init];
        vc.navigationItem.title = @"切换账号";
        [[XLAccountManager shareInstance] removeUserInfo];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
        [self presentViewController:nav animated:YES completion:^{
            
        }];
    };
    _setCell = setcell;
    
   
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"0"]) {//不是主播
        self.cellArray = @[ /*@[blackList],*/ @[huanchuncell,guanyucell],@[setcell]];
    } else {//是主播
        self.cellArray = @[@[swcell /*,blackList*/ ], @[huanchuncell,guanyucell],@[setcell]];
    }
}
- (void)toSaveUserInfo {
    NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:UserID];
    @weakify(self);
    [[[XLHTTPSessionManager sharedManager] getSetStatusOfAnchorLiveChatAnchorld:uid IsLive:self.videoSwitchValue] subscribeNext:^(id x) {
        @strongify(self);
        NSString * successState = [NSString stringWithFormat:@"%@",x[@"success"]];
        if ([successState isEqualToString:@"0"]) {
            if (self.setChatSucessBlock) {
                self.setChatSucessBlock();
            }
            //            [self downloadUserInfor];
            [HelpTool startTipViewWithText:self.videoHint duration:2.0f type:kTipViewTypeNone];
        }else{
            if (self.setChatFailBlock) {
                self.setChatFailBlock();
            }
            [HelpTool startTipViewWithText:@"设置失败" duration:2.0f type:kTipViewTypeNone];
        }
    } error:^(NSError *error) {
        if (self.setChatFailBlock) {
            self.setChatFailBlock();
        }
        [HelpTool startTipViewWithText:@"设置失败" duration:2.0f type:kTipViewTypeNone];
    }];
    
}
- (NSString *)calculateCacheSize {
    YYWebImageManager *manager = [YYWebImageManager sharedManager];
    self.bytes = [manager.cache.diskCache totalCost];
    if (self.bytes <= 0) {
        return @"0 M";
    } else if (self.bytes < 1024) {
        return F(@"%lu B", (unsigned long)self.bytes);
    } else if (self.bytes < 1024 * 1024) {
        return F(@"%.1f KB", self.bytes / 1024.0);
    } else if (self.bytes < 1024 * 1024 *  1024) {
        return F(@"%.1f M", self.bytes / 1024.0 / 1024.0);
    } else {
        return F(@"%.1f G", self.bytes / 1024.0 / 1024.0 / 1024.0);
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
